package com.example.tests;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import ru.esteru.selenium.factory.WebDriverFactory;

public class deleteNewUserTest {
	private WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();
	
	@Before
	public void setUp() throws Exception {
		driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
		baseUrl = "http://localhost/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
	}

	
	@Test
	public void DeleteNewUser() {
		goToMainPage();
		logInAs("admin", "admin");
		goToUserManagementPage();
		deleteNewUser();
		logOut();
	}
	
	private void deleteNewUser() {
		driver.findElement(By.cssSelector("img[alt=\"Remove\"]")).click();
		driver.switchTo().alert().accept();

		
	}

	
	private void goToUserManagementPage() {
		//go to User Management Page
		driver.findElement(By.linkText("User management")).click();

		
	}

		private void logOut() {
		//logout
		driver.findElement(By.linkText("Log out")).click();
		driver.switchTo().alert().accept();
	}

	private void logInAs(String username, String password) {
		//login as
		driver.findElement(By.id("username")).clear();
		driver.findElement(By.id("username")).sendKeys(username);
		driver.findElement(By.name("password")).clear();
		driver.findElement(By.name("password")).sendKeys(password);
		driver.findElement(By.name("submit")).click();
		assertTrue(isElementPresent(By.linkText("Log out")));
	}

	private void goToMainPage() {
		//go to mainpage
		driver.get(baseUrl + "/php4dvd/");
	}

	
	
	@After
	public void tearDown() throws Exception {
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
